#include "mbed.h"
#include "TextLCD.h"

#include "game.h"

TextLCD lcd(p15,p16,p17,p18,p19,p20);
Serial pc(USBTX,USBRX);
BusOut rows(p26,p25,p24);
BusIn cols(p14,p13,p12,p11);

char Keytable[] = {
    'F','E','D','C',
    '3','6','9','B',
    '2','5','8','0',
    '1','4','7','A'
    };

int main(void){
    int secretNum = enterNumber();
    lcd.cls();
    lcd.printf("The secret is %d",secretNum);
    pc.printf("%d",secretNum);//发送秘密数字      //改进：可以模仿TCP/IP协议，进行握手和挥手
    wait(1);
    
    int getScore = 0;
    //pc.scanf("%s",getScore);//term上调试通过，c程序中未通过
    //pc.scanf("%d",&getScore);
    getScore = (int)pc.getc();//读取
    //pc.gets(getScore,LEN);//能读取到空格和回车
    lcd.locate(0,1);
    lcd.printf("Score:%d",getScore);
    }

/*getKeyCharacter*/                                                       //读取键盘字母
char getKey(void){
    int i,j;
    char ch = ' ';
    
    for(i = 0;i <= 3;i++){
        rows = i;
        for(j = 0;j <= 3;j++){
            if(((cols ^ 0x00FF) & (0x0001 << j)) != 0){
                ch = Keytable[(i * 4) + j];
                }
            }  
        }
        return ch;
    }
    
/*get enter number*/                                                 //读取用户输出的数字
int enterNumber(void){
    char ch = '0';//键盘输入的数字
    int i = 0;//数字插入下标
    int num[2];//存储输入数字
    int secretNum = 0;//猜测数字
    lcd.cls();
    lcd.locate(0,0);
    lcd.printf("enter number:\n");
    while(ch != 'C'){     
        ch = getKey();
        while(ch == ' '){//当键盘未按下时，间隔0.1s,重复读取
            wait(0.01);
            ch = getKey();
            }
        
        lcd.printf("%c",ch);//输出所按下的数字
        wait(0.5);
        if((ch == '0') && (i == 0)){
            num[0] = 0;
            num[1] = 0;
            break;
            }
        switch(ch){
            case '0':num[i] = 0;break;
            case '1':num[i] = 1;i++;break;
            case '2':num[i] = 2;i++;break;
            case '3':num[i] = 3;i++;break;
            case '4':num[i] = 4;i++;break; 
            case '5':num[i] = 5;i++;break;
            case '6':num[i] = 6;i++;break; 
            case '7':num[i] = 7;i++;break;
            case '8':num[i] = 8;i++;break;
            case '9':num[i] = 9;i++;break;
            case 'C':break;
            default:
                lcd.cls();
                lcd.printf("enter number\nfrom 0 to 30");
            }
        }//while end//读取结束
        if(i > 1){
            secretNum = num[0]*10 + num[1];
            lcd.cls();
            lcd.printf("%d",secretNum);
            }
        if(i == 1){
            secretNum = num[0];
            lcd.cls();
            lcd.printf("%d",secretNum);
            }
            return secretNum;
            }